package net.hn.hnms.biz.plan.group.service.impl;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import net.hn.hnms.biz.plan.group.service.GroupBigScreenSerevice;
import net.hn.hnms.biz.plan.mapper.GroupBigScreenMapper;
import net.hn.hnms.biz.plan.vo.*;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.core.exception.HuaNengException;
import net.hn.hnms.sys.common.core.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;
@Slf4j
@Service
public class GroupBigScreenServiceImpl implements GroupBigScreenSerevice {


    @Autowired
    private GroupBigScreenMapper groupBigScreenMapper;

    @Override
    public CoalMiningTotalVo getDailyOutputStatus(Integer type, String orgCode) {
        DynamicDataSourceContextHolder.push("dm");
        if(type==null||type>3||type<1){
            throw new HuaNengException(Constants.FAIL, "参数不正确");
        }
        LocalTime currentTime = LocalTime.now();
        Integer mark = null;
        if (currentTime.isAfter(LocalTime.of(0, 0)) && currentTime.isBefore(LocalTime.of(8, 0))) {
//            System.out.println("当前时间在0点和8点之间"+LocalTime.now());
            log.info("当前时间在0点和8点之间"+LocalTime.now());
            mark = 2;
        } else {
//            System.out.println("");
            log.info("当前时间不在0点和8点之间");
            mark = 1;
        }
        CoalMiningTotalVo dailyOutputStatus = new CoalMiningTotalVo();
        if (orgCode == null || "".equals(orgCode)) {
            dailyOutputStatus = groupBigScreenMapper.getDailyOutputStatus(type,mark);
        }else{
            dailyOutputStatus = groupBigScreenMapper.getDailyOutputStatusByOrgCode(type,mark,orgCode);
        }
        DynamicDataSourceContextHolder.clear();
        return dailyOutputStatus;
    }

    @Override
    public List<CoalMiningTotalVo> getCompletionRateRanking(Integer type,Integer flag) {
        DynamicDataSourceContextHolder.push("dm");
        if(type==null||type>3||type<1){
            throw new HuaNengException(Constants.FAIL, "参数不正确");
        }
        if(type==null||flag>4||flag<1){
            throw new HuaNengException(Constants.FAIL, "参数不正确");
        }
        LocalTime currentTime = LocalTime.now();
        Integer mark = null;
        if (currentTime.isAfter(LocalTime.of(0, 0)) && currentTime.isBefore(LocalTime.of(8, 0))) {
            System.out.println("当前时间在0点和8点之间"+LocalTime.now());
            mark = 2;
        } else {
            System.out.println("当前时间不在0点和8点之间");
            mark = 1;
        }
        List<CoalMiningTotalVo> completionRateRanking = groupBigScreenMapper.getCompletionRateRanking(type, flag,mark);
        DynamicDataSourceContextHolder.clear();
        return completionRateRanking;
    }

    @Override
    public  List<CoalMiningTotalVo> getPlanAndActualContrast(Integer type, Integer level,Integer flag, String companyCode) {
        if(type==null||type>3||type<1){
            throw new HuaNengException(Constants.FAIL, "参数不正确");
        }
        LocalTime currentTime = LocalTime.now();
        Integer mark = null;
        if (currentTime.isAfter(LocalTime.of(0, 0)) && currentTime.isBefore(LocalTime.of(8, 0))) {
            System.out.println("当前时间在0点和8点之间"+LocalTime.now());
            mark = 2;
        } else {
            System.out.println("当前时间不在0点和8点之间");
            mark = 1;
        }
        DynamicDataSourceContextHolder.push("dm");
        List<CoalMiningTotalVo> planAndActualContrast = groupBigScreenMapper.getPlanAndActualContrast(type, level,flag,mark);
        DynamicDataSourceContextHolder.clear();
        //如果公司编码是扎煤，只返回扎煤下矿数据
        if (StringUtils.isNotEmpty(companyCode)) {
            if (companyCode.equalsIgnoreCase("91150781720169744B") && type == 3) {
                Set<String> keysToKeep = new HashSet<>(Arrays.asList("灵露煤矿", "灵泉煤矿", "铁北煤矿", "灵东煤矿"));
                // 只保留orgFullName在keysToKeep中的数据
                planAndActualContrast.removeIf(v -> !keysToKeep.contains(v.getOrgFullName()));
            }
        }
        return planAndActualContrast;
    }

    @Override

    public    Map<String, List<CoalMiningTotalVo>> getTrendProductionAndSale(Integer type, Integer level) {
        List<CoalMiningTotalVo> monthOuputVOList = new ArrayList<>();
        LocalTime currentTime = LocalTime.now();
        Integer mark = null;
        if (currentTime.isAfter(LocalTime.of(0, 0)) && currentTime.isBefore(LocalTime.of(8, 0))) {
            System.out.println("当前时间在0点和8点之间"+LocalTime.now());
            mark = 2;
        } else {
            System.out.println("当前时间不在0点和8点之间");
            mark = 1;
        }
        List<String> orderGroup1 = Arrays.asList("总计", "华亭", "扎煤", "陕西", "庆阳");
        List<String> orderGroup2 = Arrays.asList("总计","煤业公司", "北方公司", "蒙东公司");
        List<String> selectedOrder ;
        DynamicDataSourceContextHolder.push("dm");
        if((type == 1 && level == 1)) {//近10年 煤炭产业
//            throw new HuaNengException(Constants.FAIL, "参数不正确");
            monthOuputVOList = groupBigScreenMapper.recentlyTenYearsByIndustry(1);
            selectedOrder = orderGroup2;
        }else if (type == 2 && level==1) { //近12月  煤炭产业-------------
            monthOuputVOList = groupBigScreenMapper.recentlyTwelveMonthsByIndustry(1,mark);
            selectedOrder = orderGroup2;
        }else if(type == 3 && level==1){ //近30天  煤炭产业
            monthOuputVOList = groupBigScreenMapper.recentlyThirtyDaysByIndustry(1,mark);
            selectedOrder = orderGroup2;
        }else if(type == 1 && level==2){//近10年 煤业公司
//            throw new HuaNengException(Constants.FAIL, "参数不正确");
            monthOuputVOList = groupBigScreenMapper.recentlyTenYearsByIndustry(2);
            selectedOrder = orderGroup1;
        } else if (type == 2 && level ==2) { //近12 月 煤业公司
            monthOuputVOList = groupBigScreenMapper.recentlyTwelveMonthsByIndustry(2,mark);
            selectedOrder = orderGroup1;
        } else if (type == 3 && level == 2) { //近30天 煤业公司
            monthOuputVOList = groupBigScreenMapper.recentlyThirtyDaysByIndustry(2,mark);
            selectedOrder = orderGroup1;
        }
//        else if (type == 2 && level == 3) { //近12月 煤矿
//            monthOuputVOList = groupBigScreenMapper.recentlyThirtyDaysByIndustry(2,mark);
//            selectedOrder = orderGroup1;
//        }else if (type == 1 && level == 3) { //近10月 煤矿
//            monthOuputVOList = groupBigScreenMapper.recentlyThirtyDaysByIndustry(2,mark);
//            selectedOrder = orderGroup1;
//        }
        else {
            throw new HuaNengException(Constants.FAIL, "参数不正确");
        }
        DynamicDataSourceContextHolder.clear();






        // 按组织名称分组
//        Map<String, List<CoalMiningTotalVo>> groupedByOrg = monthOuputVOList.stream()
//                .collect(Collectors.groupingBy(CoalMiningTotalVo::getOrgShortName));

        // 对每个组织的列表按日期排序
//        Map<String, List<CoalMiningTotalVo>> sortedGroupedByOrg = groupedByOrg.entrySet().stream()
//                .collect(Collectors.toMap(
//                        Map.Entry::getKey,
//                        entry -> entry.getValue().stream()
//                                .sorted(Comparator.comparing(CoalMiningTotalVo::getStYear, Comparator.nullsLast(Comparator.naturalOrder())))
//                                .collect(Collectors.toList()),
//                        (existing, replacement) -> existing,
//                        LinkedHashMap::new
//                ));


        // 按组织名称分组
        Map<String, List<CoalMiningTotalVo>> groupedByOrg = monthOuputVOList.stream()
                .filter(vo -> vo.getOrgShortName() != null)
                .collect(Collectors.groupingBy(CoalMiningTotalVo::getOrgShortName));


                Map<String, List<CoalMiningTotalVo>> sortedGroupedByOrg1 = groupedByOrg.entrySet().stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry -> entry.getValue().stream()
                                .sorted(Comparator.comparing(CoalMiningTotalVo::getStYear, Comparator.nullsLast(Comparator.naturalOrder())))
                                .collect(Collectors.toList()),
                        (existing, replacement) -> existing,
                        LinkedHashMap::new
                ));

        // 按 selectedOrder 排序 groupedByOrg 的键
        Map<String, List<CoalMiningTotalVo>> sortedGroupedByOrg = sortedGroupedByOrg1.entrySet().stream()
                .sorted(Map.Entry.comparingByKey(Comparator.comparingInt(selectedOrder::indexOf)))
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (e1, e2) -> e1,
                        LinkedHashMap::new
                ));

        // 打印结果
        sortedGroupedByOrg.forEach((orgName, dataList) -> {
            System.out.println("Organization: " + orgName);
            dataList.forEach(vo -> System.out.println("Date: " + vo.getStYear()));
        });


        return sortedGroupedByOrg;
    }

    @Override
    public List<WorkTrackingInfoVo> getWorkTrackingInfo(String orgCode, String code) {
        DynamicDataSourceContextHolder.push("dim");
        List<WorkTrackingInfoVo> workTrackingInfo = groupBigScreenMapper.getWorkTrackingInfo(orgCode,code);
        DynamicDataSourceContextHolder.clear();
        return workTrackingInfo;
    }

    @Override
    public List<MineNumberVo> getMineNumberStatus(String orgCode) {
        DynamicDataSourceContextHolder.push("dim");
        List<MineNumberVo> mineNumber = groupBigScreenMapper.getMineNumber(orgCode);
        DynamicDataSourceContextHolder.clear();
        return mineNumber;
    }

    @Override
    public List<CoalMiningTotalVo> getStock(Integer type,String companyCode) {
        LocalTime currentTime = LocalTime.now();
        Integer mark = null;
        if (currentTime.isAfter(LocalTime.of(0, 0)) && currentTime.isBefore(LocalTime.of(8, 0))) {
            System.out.println("当前时间在0点和8点之间"+LocalTime.now());
            mark = 2;
        } else {
            System.out.println("当前时间不在0点和8点之间");
            mark = 1;
        }
        DynamicDataSourceContextHolder.push("dm");
        List<CoalMiningTotalVo> stock = groupBigScreenMapper.getStock(type,mark);
        DynamicDataSourceContextHolder.clear();
        //如果公司编码是扎煤，只返回扎煤下矿数据
        if (StringUtils.isNotEmpty(companyCode)) {
            if (companyCode.equalsIgnoreCase("91150781720169744B") && type == 3) {
                Set<String> keysToKeep = new HashSet<>(Arrays.asList("灵露煤矿", "灵泉煤矿", "铁北煤矿", "灵东煤矿"));
                // 只保留orgFullName在keysToKeep中的数据
                stock.removeIf(v -> !keysToKeep.contains(v.getOrgFullName()));
            }
        }

        return stock;
    }

    @Override
    public List<CoalMiningYoyMomVo> getSameRingCompare(Integer type) {
        LocalTime currentTime = LocalTime.now();
        Integer mark = null;
        if (currentTime.isAfter(LocalTime.of(0, 0)) && currentTime.isBefore(LocalTime.of(8, 0))) {
            System.out.println("当前时间在0点和8点之间"+LocalTime.now());
            mark = 2;
        } else {
            System.out.println("当前时间不在0点和8点之间");
            mark = 1;
        }
        DynamicDataSourceContextHolder.push("dws");
        List<CoalMiningYoyMomVo> sameRingCompare = groupBigScreenMapper.getSameRingCompare(type,mark);
        DynamicDataSourceContextHolder.clear();
        return sameRingCompare;
    }

    @Override
    public List<MineInfoVo> getMineInfo(Integer type) {
        DynamicDataSourceContextHolder.push("dim");
        List<MineInfoVo> mineInfo = groupBigScreenMapper.getMineInfo(type);
        DynamicDataSourceContextHolder.clear();
        return mineInfo;
    }

    @Override
    public List<MineInfoVo> getSafetyMineInfo(String type) {
        DynamicDataSourceContextHolder.push("dim");
        List<MineInfoVo> mine = groupBigScreenMapper.getMineInfo(null);
        DynamicDataSourceContextHolder.clear();
        DynamicDataSourceContextHolder.push("dws");
        List<MineInfoVo> mineInfo = groupBigScreenMapper.getSafetyMineInfo(type);
        DynamicDataSourceContextHolder.clear();
        if (StringUtils.isNotBlank(type)){
            List<String> collect = mine.stream().filter(u -> StringUtils.equals(u.getMiningMethodTypes(), type)).map(MineInfoVo::getMkCode).collect(Collectors.toList());
            mineInfo = mineInfo.stream().filter(u -> collect.contains(u.getMkCode())).collect(Collectors.toList());
        }
        return mineInfo;
    }

    @Override
    public List<MineInfoVo> getMineProdCapacity(String companyCode) {
        DynamicDataSourceContextHolder.push("dim");
        List<MineInfoVo> mineInfo = groupBigScreenMapper.getMineProdCapacity(companyCode);
        DynamicDataSourceContextHolder.clear();
        return mineInfo;
    }

    @Override
    public List<MineInfoVo> getMineWorkingFaceStatus(String companyCode) {
        DynamicDataSourceContextHolder.push("dim");
        List<MineInfoVo> mineInfo = groupBigScreenMapper.getMineWorkingFaceStatus(companyCode);
        DynamicDataSourceContextHolder.clear();
        return mineInfo;
    }

    @Override
    public List<MineInfoVo> getDrivingWorkingFace(String code) {
        DynamicDataSourceContextHolder.push("dim");
        List<MineInfoVo> drivingWorkingFace = groupBigScreenMapper.getDrivingWorkingFace(code);
        DynamicDataSourceContextHolder.clear();
        return drivingWorkingFace;
    }

    @Override
    public List<MineInfoVo> getDrivingWorkingFaceMine(String type) {
        if(!type.equals("井工矿")&&!type.equals("露天矿")){
            throw new HuaNengException(Constants.FAIL, "参数不正确");
        }
        DynamicDataSourceContextHolder.push("dim");
        List<MineInfoVo> drivingWorkingFaceMine = groupBigScreenMapper.getDrivingWorkingFaceMine(type);
        DynamicDataSourceContextHolder.clear();
        return drivingWorkingFaceMine;
    }

    @Override
    public List<MineInfoVo> getTrendDrivingAndStripped(String Name,Integer type,String WorkingFace,Integer flag) {
        LocalTime currentTime = LocalTime.now();
        Integer mark = null;
        if (currentTime.isAfter(LocalTime.of(0, 0)) && currentTime.isBefore(LocalTime.of(8, 0))) {
            System.out.println("当前时间在0点和8点之间"+LocalTime.now());
            mark = 2;
        } else {
            System.out.println("当前时间不在0点和8点之间");
            mark = 1;
        }
        DynamicDataSourceContextHolder.push("dm");
        List<MineInfoVo> trendDrivingAndStripped = groupBigScreenMapper.getTrendDrivingAndStripped(Name, type, WorkingFace,mark,flag);
        DynamicDataSourceContextHolder.clear();
        return trendDrivingAndStripped;
    }

    @Override
    public List<EnvironmentRankingVo> getEnvironmentalMonthlyAssessmentRanking() {
        return groupBigScreenMapper.getEnvironmentalMonthlyAssessmentRanking();
    }

    @Override
    public List<EfficientTransmissionVo> getEnvironmentalEfficientTransmission() {
        return groupBigScreenMapper.getEnvironmentalEfficientTransmission();

    }
}
